<?php
require 'DataBaseConnection.php';

class ShoppingCartMySQL
{
	public $databaseConnection;
	protected $orderid;

	public function __construct($database, $user, $password)
	{
		$server = 'mysql:host=localhost;dbname=' . $database;

		$options  = array
		(
				PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
				PDO::MYSQL_ATTR_READ_DEFAULT_FILE => '/etc/my.cnf',
				PDO::ATTR_ERRMODE,
				PDO::ERRMODE_EXCEPTION
		);
		try
		{

			$this->databaseConnection = new DataBaseConnection($server, $user, $password, $options);
		}
		catch (PDOException $e)
		{
			die('Fehler beim Verbindungsbaufbau:' . $e->getMessage());
		}

	}

	// Set current item ID
	public function setOrderid($orderid)
	{
		$this->orderid = $orderid;
	}

	public function getNextFreeOrderID()
	{
		try
		{
			$stmt = $this->databaseConnection->pdo->prepare("SELECT orderid FROM item WHERE orderid=(SELECT max(orderid) FROM item);");
			$stmt->execue();

			$maxOrderId = $stmt->fetch();
			return $maxOrderId++;

		}
		catch (PDOException $e)
		{
			die('Fehler beim Verbindungsbaufbau:' . $e->getMessage());
		}
	}

	// Add an item to database
	public function add($name,$price,$quantity)
	{
		if (!isset($this->orderid))
			die("Es wurde keine Orderid gesetzt");

		try
		{
			$stmt = $this->databaseConnection->pdo->prepare("INSERT INTO item (orderid,name,quantity,price) VALUES (:orderid, :name, :quantity, :price)");
			$stmt->bindParam(':orderid', $this->orderid);
			$stmt->bindParam(':name', $name);
			$stmt->bindParam(':quantity', $quantity);
			$stmt->bindValue(':price', $price);

			$stmt->execute();
		}
		catch (PDOException $e)
		{
			die('Fehler beim Verbindungsbaufbau:' . $e->getMessage());
		}
	}

	public function delete($name,$quantity)
	{
		if (!isset($this->orderid))
			die('Es wurde keine Orderid gesetzt');
		 
		else
		{
			$stmt = $this->databaseConnection->pdo->prepare("SELECT quantity FROM item WHERE name = :name AND orderid = :orderid");
			$stmt->bindParam(':name', $name);
			$stmt->bindParam(':orderid', $this->orderid);
			$stmt->execute();
			$result = $stmt->fetch(PDO::FETCH_ASSOC);

			if (isset($result))
			{
				// If quantity in database bigger than delete quantity => update
				if ($result['quantity'] > $quantity)
				{
					$newQuantity = $result['quantity'] - $quantity;

					$stmt = $this->databaseConnection->pdo->prepare("UPDATE item SET quantity = :quantity WHERE orderid = :orderid AND name = :name");
					$stmt->bindParam(':name', $name);
					$stmt->bindParam(':orderid', $this->orderid);
					$stmt->bindParam(':quantity', $newQuantity);
					$result = $stmt->execute();
				}
				// Delete item in database, because quantity in database is lower than delete quantity
				else
				{
					$stmt = $this->databaseConnection->pdo->prepare("DELETE FROM item WHERE orderid = :orderid AND name = :name");
					$stmt->bindParam(':name', $name);
					$stmt->bindParam(':orderid', $this->orderid);
					$result = $stmt->execute();
				}
			}
		}
	}

	public function subtotal()
	{
		if (!isset($this->orderid))
			die('Es wurde keine Orderid gesetzt');

		$total = 0;

		$stmt = $this->databaseConnection->pdo->prepare("SELECT quantity, price FROM item WHERE orderid = :orderid");
		$stmt->bindParam(":orderid", $this->orderid);
		$stmt->execute();
		$rows = $stmt->fetchAll(PDO::FETCH_BOTH);

		foreach ($rows as $row)
		{
			$total += $row['quantity'] * $row['price'];
		}

		return round($total, 2);
	}

	public function display()
	{
		if (!isset($this->orderid))
			die('Es wurde keine Orderid gesetzt');

		$output = '<table border="1">';
		$output .= '<tr><th>Name</th><th>Preis</th><th>Anzahl</th></tr>';

		$stmt = $this->databaseConnection->pdo->prepare("SELECT name, price, quantity FROM item WHERE orderid = :orderid");
		$stmt->bindParam(":orderid", $this->orderid);
		$stmt->execute();
		$rows = $stmt->fetchAll();

		foreach ($rows as $row)
		{
			$output .= '<tr><td>' . $row['name'] . '</td><td>' . $row['price'] . '</td><td>' . $row['quantity'] . '</td></tr>';
		}

		$total = $this->subtotal();
		$output .= "<tr><td>Summe: </td><td colspan='2' align='right'>" . $total ."</td></tr>";
		$output .= '</table>';

		echo $output;
	}
	
	public function getAllProducts()
	{
		try
		{	 
			$stmt = $this->databaseConnection->pdo->prepare("SELECT * FROM product");
			$stmt->execute();
			$result = $stmt->fetchAll(PDO::FETCH_OBJ);
	
			return $result;
		}
		catch(PDOException $e)
		{
			throw new ErrorException("Databaseconnection is not available");
		}
	}
	
	public function getProduct($id)
	{
		try
		{
			$stmt = $this->databaseConnection->pdo->prepare("SELECT * FROM product WHERE id = :id");
			$stmt->bindParam(":id", $id);
			$stmt->execute();
			$result = $stmt->fetch(PDO::FETCH_OBJ);
			 
			return $result;
		}
		catch(PDOException $e)
		{
			throw new ErrorException("Databaseconnection is not available");
		}
	}
	
	public function getUserID($username)
	{
		$stmt = $this->databaseConnection->pdo->prepare("SELECT userid FROM user WHERE name = :username");
		$stmt->bindParam(":username", $username);
		$stmt->execute();
		
		$result = $stmt->fetch(PDO::FETCH_OBJ);
		if (isset($result))
		{
			return $result->userid;
		}
		
		return null;
	}
}